define(['knockout', 'platform.common', 'bootbox', 'knockout-bsTable', 'knockout-component', 'sco.msg', 'websocket'], function (ko, platform) {
    /**
     *
     * @type {{get: get, remove: remove, view: view, calculate: calculate}}
     */
    var rest = {
        remove: function (id) {
            var param = {};
            param.tran_id = id;
            platform.servicebreakAsync('~/rest/tran/delete', param, 'post').done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('DELSUC');
                    viewModel.tableViewModel.refresh();
                } else {
                    platform.showErrorTip(response.meta.message);
                }
            });
        },
        calculate: function (param) {
            // var param = {};
            // param.tran_id = id;
            // param.code = code;
            platform.servicebreakAsync('~/rest/theory/calculate', param, 'post').done(function (response) {
                if (response instanceof Object) {
                    if (null != response.meta) {
                        if (!response.meta.success) {//计算成功
                            if (viewModel.calProgressModel.processMsg() != undefined
                                && viewModel.calProgressModel.processMsg() != null
                                && viewModel.calProgressModel.processMsg() != '') {
                                viewModel.calProgressModel.processMsg(viewModel.calProgressModel.processMsg() + '\n' + response.meta.message);
                            } else {
                                viewModel.calProgressModel.processMsg(response.meta.message);
                            }

                            viewModel.calProgressModel.isEnabled(true);
                        }
                    }
                }
            });
        }
    };
    var socket = new websocket();
    var kbTable = require('knockout-bsTable');
    var bootbox = require('bootbox');

    var tgOpts = platform.servicebreak("~/rest/tg/getTgDict").responseJSON.responseObject;
    var modelTypes = platform.servicebreak("~/rest/modelLib/getModelLibByType", {model_type: '01'}).responseJSON.responseObject;
    var VM = function () {
        var self = this;
        self.fixedTgId = ko.observable();
        self.tgOpts = ko.computed(function () {
            return tgOpts;
        });
        self.columns = [{checkbox: true, align: 'center', width: 30}, {
            field: 'display_order', title: '序号',
            formatter: function (value, row, index) {
                var options = self.tableViewModel.getOptions();
                var indexPageNum = parseInt(options.pageNumber);
                var indexPageSize = parseInt(options.pageSize);
                return ((indexPageNum - 1) * indexPageSize)
                    + (index + 1);
            },
            width: 35, align: 'center'
        }, {field: 'tran_id', title: '配变标识', width: 120, visible: false}, {
            field: 'tran_no',
            title: '配变编号',
            width: 120,
            align: 'left'
        }, {field: 'tran_name', title: '配变名称', width: 120}, {
            field: 'tran_model',
            title: '型号',
            width: 80,
            align: 'center', formatter: function (value, row, index) {
                var showText = null;
                $.each(modelTypes, function (index, node) {
                    if (node.model_id === value) {
                        showText = node.model_no;
                    }
                });
                return showText;
            }
        }, {field: 'tran_capacity', title: '容量(kVA)', width: 60, align: 'right'}, {
            field: 'tg_id',
            title: '所属台区',
            width: 80,
            align: 'left', formatter: function (value, row, index) {
                var showText = null;
                $.each(tgOpts, function (index, node) {
                    if (node.tg_id === value) {
                        showText = node.tg_name;
                    }
                });
                return showText;
            }
        }, {field: 'section_date', title: '断面日期', width: 100, align: 'center'}, {
            field: 'record_date',
            title: '记录日期',
            width: 120,
            align: 'center'
        }];
        self.tableViewModel = new kbTable.bootstrapTableViewModel({
            url: platform.mapUrl('~/rest/tran/list'),
            toolbar: '#toolbar',
            queryParams: function (params) {
                return {
                    pageNumber: params.offset / params.limit + 1,
                    pageSize: params.limit,
                    tg_id: self.fixedTgId()
                };
            },
            columns: self.columns
        });
        self.cpModelVisible = ko.observable(false);
        self.calProgressModel = {
            title: ko.observable(),
            processMsg: ko.observable(),
            tranId: ko.observable(),
            avgVolt: ko.observable('0.38'),
            consVolt:ko.observable('0.22'),
            avgLength:ko.observable('10'),
            dataRange: ko.observable('24'),
            otherVal: ko.observable(),
            tgStructure:ko.observable('3.5'),
            tgType:ko.observable('1.25'),
            isEnabled: ko.observable(true),

            // dataRangeOptions:[
            //     {droValue:'24',droText:'24'},
            //     {droValue:'1',droText:'1'},
            //     {droValue:'3',droText:'3'},
            //     {droValue:'6',droText:'6'},
            //     {droValue:'9',droText:'9'},
            //     {droValue:'12',droText:'12'},
            //     {droValue:'0',droText:'其他'}],
            showForm: function (id) {
                this.title('标杆值计算进度');
                $('#calInfoForm').resetForm();
                this.tranId(id);
                this.otherVal('');
                this.dataRange('24');
                $('#avgVolt').val('0.38');
                this.avgVolt('0.38');
                $('#consVolt').val('0.22');
                this.consVolt('0.22');
                $('#avgLength').val('10');
                this.avgLength('10');
                this.tgStructure('3.5');
                this.tgType('1.25');
                self.cpModelVisible(true);
            },
            calculate: function () {
                this.processMsg('');
                var that = this;
                // socket = new websocket();
                var param = {};
                param.tran_id = that.tranId();
                param.code = socket.code;
                param.avgVolt = that.avgVolt();
                param.consVolt = that.consVolt();
                param.consLength = that.avgLength();
                param.tgStruArgs = that.tgStructure();
                param.tgType = that.tgType();

                if (that.dataRange() === '0') {
                    if (that.otherVal() === null || that.otherVal() == '') {
                        platform.showWarnTip('请填写正确的数据计算时间范围!');
                        return;
                    } else {
                        param.calCycle = that.otherVal();
                    }

                } else {
                    param.calCycle = that.dataRange();
                }

                rest.calculate(param);
                socket.init({
                    onmessage: function (msg) {
                        // console.log("----------------------");
                        if (that.processMsg() == undefined || that.processMsg() == '') {
                            that.processMsg(msg);
                        } else {
                            that.processMsg(that.processMsg() + '\n' + msg);
                        }
                    }
                });

                that.isEnabled(false);
            },
            close: function () {
                // if (null != socket) {
                //     socket.close();
                // }
                this.processMsg('');
                self.cpModelVisible(false);
                this.isEnabled(true);
                $('#calculateProgressDlg').toggleClass('hide');
            }
        };
        self.webCode = ko.observable();
        self.editModelVisible = ko.observable(false);
        self.tranViewEditModel = {
            title: ko.observable(),
        };
        self.viewModelVisible = ko.observable(false);
        self.tranViewModel = {
            title: ko.observable(),
            close: function () {

            }
        };
        /**
         * 方法定义
         */
        self.fnRemove = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                bootbox.confirm({
                    title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                    size: 'small',
                    message: '删除变压器时，将级联删除其关联的如低压线路、线路分段、低压用户等信息及电量数据，确认是否删除?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (response) {
                        if (response) {
                            var id = selections[0].tran_id;
                            rest.remove(id);
                        }
                    }
                });

            } else {
                platform.showTip('remove');
            }
        };
        self.fnView = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].tran_id;
            } else {
                platform.showTip('view');
            }
        };
        self.fnCal = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].tran_id;
                self.calProgressModel.showForm(id);
                $('#calculateProgressDlg').toggleClass('hide');
            } else {
                platform.showTip('calculate');
            }
        };
        self.fnSearch = function () {
            var param = {};
            param.tg_id = self.fixedTgId();
            self.tableViewModel.refresh(param);
        };
    };
    var viewModel = new VM();
    return viewModel;
});